package com.itheima.untils;

import com.itheima.pojo.Setmeal;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class FreemarkUtils {
    private static FreeMarkerConfigurer freeMarkerConfigurer;
    /*
     * 获取配置文件属性值*/
    private static String out_put_path;
    private static JedisPool jedisPool;

    /*
     * 生成静态页面
     * */
    public static void getData(FreeMarkerConfigurer freeMarkerConfigurer,String out_put_path,JedisPool jedisPool){
        FreemarkUtils.jedisPool = jedisPool;
        FreemarkUtils.freeMarkerConfigurer = freeMarkerConfigurer;
        FreemarkUtils.out_put_path = out_put_path;
    }

    public static void generateMobileStaticHtml(Object data){

        generateMobileSetmealListHtml((List<Setmeal>) data);
        generateMobileSetmealDetailHtml((List<Setmeal>) data);
    }


    /*
     * 生成套餐列表静态页面
     * */
    public static void generateMobileSetmealListHtml(List<Setmeal> setmealList){
        Map map = new HashMap();
        map.put("setmealList",setmealList);
        generateHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    /*
     * 生成套餐详情界面显示
     *
     * */
    public static void generateMobileSetmealDetailHtml(List<Setmeal> setmealList){
        for (Setmeal setmeal : setmealList) {
            System.out.println(setmeal.getCheckGroups());
            Map map = new HashMap();
            map.put("setmeal",setmeal);
            generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);
            jedisPool.getResource().sadd("id", String.valueOf(setmeal.getId()));
        }
    }

    /**
     * 生成静态HTML  通用
     *
     */
    public static void generateHtml(String templateName, String name, Map map){
        //获取模板对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        try {
            //加载模板文件
            Template template = configuration.getTemplate(templateName);
            //创建一个流对象
            Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(out_put_path+"\\"+name)),"utf-8"));
            //创建静态HTML
            template.process(map,writer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
